<?php


namespace app\user\controller;

//分销
use app\common\model\UserIncome;
use think\Controller;
use think\db\Where;
use think\facade\Request;
use app\user\model\User as UserModel;

class Distribution extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class'
    ];

    //总共的人数
    public function data()
    {
        $user_id = Request::param('user_id');
        $sum = UserModel::where("lv_1_id=$user_id || lv_2_id=$user_id")->field('id')->count('id');
        $this->result($sum, 200, '');
    }

    //总共的人数
    public function index()
    {
        $user_id = Request::param('user_id');
        $lv = Request::param('lv', '1');       //一级分销还是二级分销
        $page = Request::param('page', 1);       //一级分销还是二级分销
        $where = [
            'user.lv_' . $lv . '_id' => $user_id
        ];

        $list = UserModel::  where($where)
            ->leftJoin('user_income', 'user.id=user_income.user_id')
            ->field('user.id , user.username, user.avatar, user.vip, sum(user_income.lv_1_income) as sum_lv_1_income ,sum(user_income.lv_2_income) as sum_lv_2_income')
            ->group('user.id')
            ->page($page, 20)
//            ->fetchSql(true)
            ->select();

//        $list = UserModel::where($where)
//            ->leftJoin('user_income', 'user.id=user_income.user_id')
//            ->field('user.id , user.username, user.avatar,  sum(user_income.lv_1_income) as sum_lv_1_income ,sum(user_income.lv_2_income) as sum_lv_2_income')
//            ->group('user_income.user_id')
//            ->page($page, 20)
//            ->select();

        $lv_1_count = UserModel::where("lv_1_id=$user_id")->field('id')->count('id');
        $lv_2_count = UserModel::where("lv_2_id=$user_id")->field('id')->count('id');

        //sum总收益
        $lv_1_sum = UserModel::where("lv_1_id=$user_id")->field('lv_1_income')->sum('lv_1_income');
        $lv_2_sum = UserModel::where("lv_2_id=$user_id")->field('lv_2_income')->sum('lv_2_income');

        $data=[
            'list'=>$list,
            "lv_1_count"=>$lv_1_count,
            "lv_2_count"=>$lv_2_count,
            "lv_1_sum"=>$lv_1_sum,
            "lv_2_sum"=>$lv_2_sum
        ];
        $this->result($data, 200, '');
    }

}
